package com.myspace.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

import com.myspace.sdk.MSRequest;
import com.myspace.sdk.MSSDK;
import com.myspace.sdk.MSRequest.MSRequestCallback;
import com.myspace.util.MSDrawableManager;

public class MSActivityStreamActivity extends MSBaseActivity {

	private static final int CREATE_ACTIVITY_DIALOG = 3;
	
	private ListView mListView;
	private ActivityListAdapter mAdapter;
	private AlertDialog mAlertDialog;
	private Button mCreateButton;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setProgressBarIndeterminateVisibility(false);  
	    
		super.onCreate(savedInstanceState);
		super.setPageName(R.string.PAGE_TITLE_ACTIVITY);
		super.setMainView(R.layout.activitystream);
				   
		mCreateButton = (Button) findViewById(R.id.createActivityButton);
		mCreateButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(CREATE_ACTIVITY_DIALOG);
			}
		});
		
		Spinner spinner = (Spinner) findViewById(R.id.selectorSpinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.activityStreamSelectors, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new SelectorSpinnerListener());
        
        mListView = (ListView) findViewById(R.id.activityList);
		mAdapter = new ActivityListAdapter(this);
		mListView.setAdapter(mAdapter);	
    }
	
	private class SelectorSpinnerListener implements OnItemSelectedListener {    
		public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
			getActivityStream(pos);
		}    

		public void onNothingSelected(AdapterView<?> parent) {      
		}
	}
	
	private void publishActivity() {
		List<Map<String,String>> msParameters = new ArrayList<Map<String,String>>();
		Map<String,String> templateParam;
		
		EditText mActivityContent = (EditText)mAlertDialog.findViewById(R.id.activityContent_edit);
		String content = mActivityContent.getText().toString();
		if(content != null && !content.equalsIgnoreCase("")) {
			templateParam = new HashMap<String,String>();
			templateParam.put("key", "content");
			templateParam.put("value", content);
			msParameters.add(templateParam);
		}
		
		if(msParameters.size() > 0) {
			MSSDK.publishActivity("Template_2", msParameters, new SetActivity_MSRequestCallback());
		}
	}

	private void getActivityStream(int pos) {
		switch(pos) {
			case 0:
				MSSDK.getActivity(new GetActivityStream_MSRequestCallback());
				break;
		}	
		setProgressBarIndeterminateVisibility(true);	
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case CREATE_ACTIVITY_DIALOG:
	            LayoutInflater factory = LayoutInflater.from(this);
	            final View textEntryView = factory.inflate(R.layout.create_activity_item, null);
	            mAlertDialog = new AlertDialog.Builder(this)
	                .setTitle("New Activity")
	                .setView(textEntryView)
	                .setPositiveButton("Submit", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    	publishActivity();
	                    }
	                })
	                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                    }
	                })
	                .create();
	            return mAlertDialog;
	    }
		return null;
	}

	private ActivityItem buildActivityItem(Map<?,?> activityObject) {
		String body = (String)activityObject.get("body");
		Date timeStamp = (Date)activityObject.get("timestamp");
		String userName = (String)activityObject.get("userName");
		String userProfileURL = (String)activityObject.get("userProfileURL");
		String userThumbnailImageURL = (String)activityObject.get("userThumbnailImageURL");
		
		ActivityItem item = new ActivityItem();
		item.setBody(body);
		item.setTimeStamp(timeStamp);
		item.setUserName(userName);
		item.setUserProfileURL(userProfileURL);
		item.setUserThumbnailImageURL(userThumbnailImageURL);
		
		return item;
	}
	
	private void updateView(List<ActivityItem> items) {
		mAdapter.clear();
		for (int i=0; i < items.size(); i++) {
			mAdapter.add(items.get(i));
		}
		mAdapter.notifyDataSetChanged();
	}
	
	private class ActivityListAdapter extends ArrayAdapter<ActivityItem> {
		private LayoutInflater mInflater;

		public ActivityListAdapter(Context context) {
			super(context, 0);
			mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = mInflater.inflate(R.layout.activity_list_item, null);

			ActivityItem item = this.getItem(position);
			
			TextView v;
			ImageView iv;
			
			if(item.getUserThumbnailImageURL() != null) {
				iv = (ImageView) view.findViewById(R.id.authorImage);
				MSDrawableManager.getInstance().fetchDrawableOnThread(item.getUserThumbnailImageURL(), iv);
			}
						
			v = (TextView) view.findViewById(R.id.activityBody);
			if(item.getBody() != null) {
				Spanned body = Html.fromHtml(item.getBody(), 
						new Html.ImageGetter() {
						@Override
						public Drawable getDrawable(String source) {
							Drawable d = MSDrawableManager.getInstance().fetchDrawable(source);
							d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 
							return d;
						}	
					}, null);
				v.setText(body, TextView.BufferType.SPANNABLE);
				v.setMovementMethod(LinkMovementMethod.getInstance());
			}
			
			v = (TextView) view.findViewById(R.id.activityPostedTime);
			if(item.getTimeStamp() != null) {
				v.setText(item.getTimeStamp().toString());
			} else {
				v.setVisibility(View.GONE);
			}
					
			return view;
		}
	}

	private class ActivityItem {
		private String mBody;
		private Date mTimeStamp;
		private String mUserThumbnailImageURL;
		
		public ActivityItem() {
		}
		
		public void setBody(String body) {
			mBody = body;
		}
		
		public String getBody() {
			return mBody;
		}
		
		public void setTimeStamp(Date timeStamp) {
			mTimeStamp = timeStamp;
		}
		
		public Date getTimeStamp() {
			return mTimeStamp;
		}
		
		public void setUserName(String userName) {
		}
		
		public void setUserProfileURL(String userProfileURL) {
		}
		
		public void setUserThumbnailImageURL(String userThumbnailImageURL) {
			mUserThumbnailImageURL = userThumbnailImageURL;
		}
		
		public String getUserThumbnailImageURL() {
			return mUserThumbnailImageURL;
		}
	}
	
	private class GetActivityStream_MSRequestCallback extends MSRequestCallback {

		public void requestDidFail(MSRequest request, Throwable error) {
            setProgressBarIndeterminateVisibility(false);
			showToast(error.getMessage());
		}

		public void requestDidLoad(MSRequest request, Object result) {
		    setProgressBarIndeterminateVisibility(false);
			
		    Map<?,?> data = (Map<?,?>)result;
			result  = data.get("data");
			
		    if(result instanceof List<?>) {
				List<ActivityItem> items = new ArrayList<ActivityItem>();
				List<?> activityList = (List<?>)result;			
				if(activityList != null && activityList.size() > 0) {
					for (int i=0; i < activityList.size(); i++) {
						Map<?,?> activityObject = (Map<?,?>) activityList.get(i);
						ActivityItem item = buildActivityItem(activityObject);
						items.add(item);
					}
					updateView(items);
				}			
			}
		}
	}

	private class SetActivity_MSRequestCallback extends MSRequestCallback {

		public void requestDidFail(MSRequest request, Throwable error) {
			showToast(error.getMessage());
		}

		public void requestDidLoad(MSRequest request, Object result) {
			showToast("Activity created successfully");
			getActivityStream(0);
		}  
	}
}